<?php
/**
 * 前台用户中心管理控制器
 * ===============================================
 * @copyright 深圳市顶速网络科技有限公司  http://fasttop.top
 * ===============================================
 * @author: Ketity <970564173@qq.com>
 * @date: 2015-6-5
 */
namespace Home\Controller;
use Common\Controller\HomeBaseController;
class UserController extends HomeBaseController {
	
	/**
	 * 初始化
	 */
	public function _initialize() {
		parent::_initialize ();
	}
	
	/**
	 * 用户登录
	 */
	public function doLogin() {
		$postdata = I ( 'post.' );
		/* 检测验证码 */
		if (C ( 'ADMIN_VERIFY' )) {
			$captcha = trim ( $postdata ['captcha'] );
			if (! D ( 'User' )->checkVerify ( $captcha )) {
				echo json_encode ( array ('code' => 0, 'msg' => L ( 'error_captcha' ) ) );
				exit ();
			}
		}
		/* 检测用户名和密码 */
		if (empty ( $postdata ['username'] ) || empty ( $postdata ['password'] )) {
			echo json_encode ( array ('code' => 0, 'msg' => L ( 'error_name_pass_empty' ) ) );
			exit ();
		}
		/* 检测登录失败次数 */
		$times = $this->_checkLoginTimes ( $postdata ['username'], 0 );
		if ($times === false) {
			echo json_encode ( array ('code' => 0, 'msg' => L ( 'error_failed_login_times' ) ) );
			exit ();
		}
		/*	用户登录	*/
		$result = $this->_login ( $postdata ['username'], $postdata ['password'], 0 );
		echo json_encode ( $result );
		exit ();
	}
	
	/**
	 * 检测登录失败次数
	 * @param string $username
	 * @param int $isadmin
	 */
	private function _checkLoginTimes($username, $isadmin) {
		$maxfailedtimes = ( int ) C ( 'MAX_LOGIN_FAILED_TIMES' );
		$locktime = ( int ) C ( 'FAILED_LOCK_TIME' );
		$rtime = D ( 'LoginTimes' )->getLoginTimes ( $username, $isadmin );
		if ($rtime && ($rtime ['times'] >= $maxfailedtimes)) {
			$minute = $locktime - floor ( (NOW_TIME - $rtime ['login_time']) / 60 );
			if ($minute > 0) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 用户登录过程处理，Ucenter开启时检测
	 * @param string $username
	 * @param string $password
	 * @param int $isadmin
	 * @param int $type
	 */
	private function _login($username, $password, $isadmin, $type = 1) {
		$uc_uid = 0;
		if (C ( 'UC_OPEN' )) { // Ucenter登录检测
			$a = uc_user_login ( $username, $password );
			list ( $uc_uid, $username, $password, $email ) = $a;
			if ($uc_uid < 0) { // Ucenter登录失败
				switch ($uc_uid) {
					case - 1 :
						$error = L ( 'error_uc_login_-1' ); // ucenter级别用户不存在或者禁用
						break;
					case - 2 :
						$error = L ( 'error_uc_login_-2' ); // ucenter级别密码错误
						break;
					default :
						$error = L ( 'error_uc_login_-3' ); // 0-接口参数错误（调试阶段使用）
						break;
				}
				return array ('code' => 0, 'msg' => $error );
			}
		}
		// 用户登录
		$where = array ();
		switch ($type) {
			case 1 :
				$field = 'username';
				break;
			case 2 :
				$field = 'email';
				break;
			case 3 :
				$field = 'mobile';
				break;
			case 4 :
				$field = 'uid';
				break;
			default :
				return 0; // 参数错误
		}
		$user = D ( 'User' )->getUser ( $field, $username ); // 获取用户数据
		if (empty ( $user )) {
			return array ('code' => 0, 'msg' => L ( 'error_login_-1' ) ); // 用户不存在
		}
		if (! $user ['status']) {
			return array ('code' => 0, 'msg' => L ( 'error_login_-2' ) ); // 用户被禁用
		}
		/* 验证用户密码 */
		if (D ( 'User' )->checkPassword ( $user ['uid'], $password )) {
			D ( 'User' )->editLoginInfo ( $user ['uid'] ); // 更新用户登录信息
			D ( 'LoginTimes' )->delLoginRecord ( $username, 0 ); // 登录成功后删除用户登录失败记录
			$this->autoLogin ( $user ['uid'], $username ); //保存用户登录session信息
			return array ('code' => 1, 'msg' => L ( 'success_login' ) ); // 登录成功，返回用户ID
		} else {
			// 密码错误，添加一次登录失败次数
			if (D ( 'LoginTimes' )->getLoginTimes ( $username, $isadmin )) {
				D ( 'LoginTimes' )->editLoginTimes ( $username, $isadmin );
			} else {
				D ( 'LoginTimes' )->addLoginTimes ( $username, $isadmin );
			}
			return array ('code' => 0, 'msg' => L ( 'error_login_-3' ) );
		}
	}
	
	/**
	 * 将用户登录信息存入session
	 * @param int $uid
	 * @param string $username
	 * @param string $expire
	 */
	protected function autoLogin($uid, $username, $expire = 86400) {
		$auth ['uid'] = $uid;
		$auth ['uname'] = $username;
		$auth ['expire'] = $expire;
		session ( 'user_auth', $auth );
		session ( 'user_auth_sign', \Org\Util\String::authSign ( $auth ) );
	}
	
	/**
	 * 用户注册
	 */
	public function register() {
		$postdata = I ( 'post.' );
		if (empty ( $postdata ['password'] )) { //密码不能为空
			echo json_encode ( array ('code' => 0, 'msg' => L ( 'error_password_empty' ) ) );
			exit ();
		}
		if ($postdata ['repwd'] != $postdata ['password']) { //密码与确认密码不一致
			echo json_encode ( array ('code' => 0, 'msg' => L ( 'error_repwd_empty' ) ) );
			exit ();
		}
		if (C ( 'UC_OPEN' )) { //开启了Ucenter
			$ucid = uc_user_register ( $postdata ['username'], $postdata ['password'], $postdata ['email'] );
			if ($ucid <= 0) {
				echo json_encode ( array ('code' => 0, 'msg' => L ( 'error_uc_register_' . $ucid ) ) );
				exit ();
			}
		}
		$info = array ('realname' => $postdata ['realname'], 'qq' => $postdata ['qq'] );
		if ($ucid) {
			$info ['ucid'] = $ucid;
		}
		$uid = D ( 'User' )->addUser ( $postdata ['username'], $postdata ['password'], $postdata ['email'], $postdata ['mobile'], $info );
		if ($uid > 0) {
			echo json_encode ( array ('code' => 1, 'msg' => L ( 'success_register' ) ) );
			exit ();
		} else {
			echo json_encode ( array ('code' => 0, 'msg' => L ( 'error_register_' . $uid ) ) );
			exit ();
		}
	}
	
	/**
	 * 退出
	 */
	public function logout() {
		if (D ( 'User' )->checkLogin ()) {
			cookie ( null );
			session ( 'user_auth', NULL );
			session ( 'user_auth_sign', NULL );
			session ( '[destroy]' ); //还是存在$_COOKIE[session_name()]
			//使用setcookie()删除包含SESSION ID的cookie
			if (isset ( $_COOKIE [session_name ()] )) {
				setcookie ( session_name (), '', time () - 3600, '/' );
			}
			$this->success ( '退出成功！', U ( 'Index/index' ) );
		} else {
			$this->redirect ( 'Index/index' );
		}
	}
	
	/**
	 * 验证码输出
	 * @access public
	 */
	public function verify() {
		$verify = new \Think\Verify ();
		$verify->entry ( 1 );
	}
	
	/**
	 * 用户修改个人资料
	 */
	public function profile() {
		$postdata = I ( 'post.' );
		$data = array (); //定义空数组
		$user = D ( 'User' )->getUser ( 'uid', session ( 'user_auth.uid' ) );
		$oldpwd = '';
		/*	修改密码	*/
		if (! empty ( $postdata ['oldpwd'] ) && ! empty ( $postdata ['newpwd'] ) && ! empty ( $postdata ['repwd'] )) {
			if ($postdata ['newpwd'] != $postdata ['repwd']) {
				echo json_encode ( array ('code' => 0, 'msg' => L ( 'error_repwd_empty' ) ) );
				exit ();
			}
			$oldpwd = $postdata ['oldpwd'];
			$data ['password'] = $postdata ['newpwd'];
			if (C ( 'UC_OPEN' )) {
				$email = $postdata ['email'] == $user ['email'] ? '' : $postdata ['email'];
				$result = uc_user_edit ( $user ['username'], $oldpwd, $data ['password'], $email );
				if ($result <= 0) {
					echo json_encode ( array ('code' => 0, 'msg' => L ( 'error_uc_edit_' . $result ) ) );
					exit ();
				}
			}
		}
		if ($data ['password']) {
			$data ['password'] = \Org\Util\String::pwd ( $data ['password'], $user ['encrypt'] );
		}
		if ($postdata ['realname'] != $user ['realname']) { //修改了真实姓名
			$data ['realname'] = $postdata ['realname'];
		}
		if ($postdata ['email'] != $user ['email']) { //修改了邮箱地址
			$data ['email'] = $postdata ['email'];
		}
		if ($postdata ['qq'] != $user ['qq']) { //修改了QQ
			$data ['qq'] = $postdata ['qq'];
		}
		if ($postdata ['mobile'] != $user ['mobile']) {
			$data ['mobile'] = $postdata ['mobile'];
		}
		if (empty ( $data )) { //数组为空，未作任何修改
			echo json_encode ( array ('code' => 0, 'msg' => L ( 'error_edit_none' ) ) );
			exit ();
		}
		$return = D ( 'User' )->editUser ( session ( 'user_auth.uid' ), $oldpwd, $data );
		if ($return == 1) {
			echo json_encode ( array ('code' => 1, 'msg' => L ( 'success_edit' ) ) );
			exit ();
		} else {
			echo json_encode ( array ('code' => 0, 'msg' => L ( $return ) ) );
			exit ();
		}
	}
}